<?php

namespace app\common\face;

use app\common\exceptions\ErrException;

class face
{
    private static $url = 'https://aip.baidubce.com/oauth/2.0/token';
    private static $access_token = '';

    protected function getBaiduAppInfo($app_name = 'GoodBo', $os_type = 'ios')
    {
        $app_info_list = [
            'GoodBo' => [
                'ios' => [
                    'api_key'    => env('baidu.api_key_ios'),
                    'secret_key' => env('baidu.secret_key_ios')
                ],
                'android' => [
                    'api_key'    => env('baidu.api_key_android'),
                    'secret_key' => env('baidu.secret_key_android')
                ],
            ],
        ];
        return $app_info_list[$app_name][$os_type];
    }

    public function index($app_name = 'GoodBo', $os_type = 'ios')
    {
        $app_info = $this->getBaiduAppInfo($app_name, $os_type);
        $post_data = [
            'grant_type'    => 'client_credentials',
            'client_id'     => $app_info['api_key'],
            'client_secret' => $app_info['secret_key'],
        ];
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);
        self::$url .= '?' . $post_data;
        $res = $this->request_post(self::$url, $post_data);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 百度实名认证
     * @param $param
     * @param $os_type
     * @param $app_name
     * @return bool
     * @throws ErrException
     */
    public function baiduVerifyFace($param, $os_type = 'ios', $app_name = 'GoodBo')
    {
        $rest = $this->index($app_name, $os_type);
        self::$access_token = $rest['access_token'];
        self::$url = "https://aip.baidubce.com/rest/2.0/face/v4/mingjing/verify?access_token=" . self::$access_token;
        $post_data = [
            'image_type'     => 'BASE64',
            'image'          => $param['image'],
            'id_card_number' => $param['id_card_number'],
            'name'           => $param['name'],
        ];
        $res = $this->request_post(self::$url, json_encode($post_data));
        $res_data = json_decode($res, true);

        if (isset($res_data['error_code'])) {
            $error_msg = "错误码：{$res_data['error_code']} ；错误信息：{$res_data['error_msg']}";
            if ($res_data['error_code'] == '222351') {
                $error_msg = "身份证号码与姓名不匹配";
            } elseif ($res_data['error_code'] == '222352') {
                $error_msg = "用户姓名 填写错误";
            } elseif ($res_data['error_code'] == '222353') {
                $error_msg = "身份证号码 填写错误";
            } elseif ($res_data['error_code'] == '222356') {
                $error_msg = "人脸采集数据模糊， 请聚焦摄像头后重新认证";
            } elseif (in_array($res_data['error_code'], ['222354', '222355', '222361'])) {
                $error_msg = "请联系客服为您处理。 错误编码：{$res_data['error_code']}";
            } elseif (in_array($res_data['error_code'], ['282105', '216201', '216100', '282003', '282000'])) {
                $error_msg = "请联系客服为您处理。{$error_msg}";
            }
            ErrException::throwExcep('-1', "人脸认证失败 - {$error_msg}");
        } elseif (isset($res_data['result']) && $res_data['result']['score'] < 60) {
            ErrException::throwExcep('-1', "人脸认证失败  - 请确认是否为本人");
        } elseif (isset($res_data['result']) && $res_data['result']['score'] >= 60) {
            return true;
        } else {
            ErrException::throwExcep('-1', "人脸认证失败 - " . json_encode($res_data));
        }
        return true;
    }

    function request_post($url = '', $param = '')
    {
        $ch         = curl_init();
        $httpHeader = [];
        $httpHeader[] = 'Content-Type:application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $result = curl_exec($ch);
        return $result;
    }
}
